<template>
  <div class="sso-loading">
    <el-icon class="is-loading" :size="30"><Loading /></el-icon>
    <span>正在登录中，请稍候...</span>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { setToken } from '@/utils/auth'
const PORTAL_LOGIN_URL = import.meta.env.VITE_APP_PORTAL_LOGIN_URL 
const APP_ID = import.meta.env.VITE_APP_ID
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

onMounted(async () => {
  const { token, msg, redirect_uri } = route.query
  
  if (token) {
    try {
      setToken(token)
      await userStore.getInfo()
     
      // 优先使用 redirect_uri，如果没有则使用 redirect，最后默认 '/'
      const targetPath = redirect_uri 
        ? decodeURIComponent(redirect_uri.replace(window.location.origin, '')) 
        : route.query.redirect || '/'
      // 确保是有效的路径（防止开放重定向漏洞）
      if (isValidPath(targetPath)) {
        router.replace(targetPath)
      } else {
        router.replace('/')
      }
    } catch (error) {
      router.replace(`/error?msg=${encodeURIComponent(error.message || '登录失败')}`)
    }
  } else if (msg) {
    router.replace(`/error?msg=${encodeURIComponent(msg)}`)
  } else {
    window.location.href = `${PORTAL_LOGIN_URL}?redirect_uri=${encodeURIComponent(window.location.href)}&client_id=${APP_ID}`
  }
})

// 辅助函数：验证路径是否合法
function isValidPath(path) {
  return /^\/[a-zA-Z0-9-_\/]*$/.test(path)
}
</script>

<style scoped>
.sso-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  gap: 20px;
  font-size: 16px;
  color: #666;
}
</style>